<?php
namespace App\Workers;

use App\Models\YikaoMajorLevel;
use Workerman\Worker;
use App\Services\SpecialMajorSpiderService;

class SpecialMajorSpiderWorker
{
    public static function run(Worker $worker, SpecialMajorSpiderService $service, $limit): void
    {
        $worker->onWorkerStart = function($worker) use ($service, $limit) {

            $options = [
                'pageSize' => 30,
                'limit' => 0,
                'proxyEnable' => false,
                'startPage' => 1
            ];

            $maxPages = PHP_INT_MAX;

            $startTime = time();
            $total = 0;
            echo "[".date('Y-m-d H:i:s')."] Worker {$worker->id} 启动\n";

            $level = YikaoMajorLevel::query()->where('parent_id', 2)->get()->toArray();
            foreach ($level as $item) {
                $currentPage = $options['startPage'];
                $totalCollected = 0;
                echo "开始采集专业 {$item['name']} \n";
                while ($currentPage <= $maxPages) {

                    echo "开始采集第 {$currentPage} 页数据 \n";

                    try {
                        $items = $service->fetchPage($item['level1'], $item['level2'], $currentPage, $options['pageSize']);
                        if (empty($items['item'])) {
                            echo "第 {$currentPage} 页无数据，采集完成 \n";
                            break;
                        }
                        $total = $items['numFound'];
                        $count = $service->saveData($items['item']);
                        $totalCollected += $count;
                        echo "第 {$currentPage} 页采集完成 \n";

                        if ($options['limit'] > 0 && $totalCollected >= $options['limit']) {
                            echo "已达到采集数量限制 {$options['limit']}，采集结束 \n";
                            break;
                        }

                        $currentPage++;
                        sleep(1); // 防止请求过于频繁

                    } catch (\Exception $e) {
                        echo "采集失败: " . $e->getMessage() . "第". $currentPage . "页" . "\n";
                        sleep(5); // 出错后等待5秒再重试
                    }
                }
                YikaoMajorLevel::query()->where('id', $item['id'])->update(['status' => 1]);
            }

            //统计结果
            $endTime = time();
            $duration = $endTime - $startTime;
            $successRate = $totalCollected > 0 ? round(($totalCollected / $total) * 100, 2) : 0;

            echo "\n===== 采集结果统计 =====\n";
            echo "开始时间: ".date('Y-m-d H:i:s', $startTime)."\n";
            echo "结束时间: ".date('Y-m-d H:i:s', $endTime)."\n";
            echo "总耗时: ".gmdate('H:i:s', $duration)."\n";
            echo "总数: {$total}\n";
            echo "成功采集: {$totalCollected}\n";
            echo "成功率: {$successRate}%\n";
            echo "平均速度: ".round($totalCollected/max(1, $duration/60), 2)." 条/分钟\n";
            echo "========================\n";
        };
    }
}
